package com.demo.server;

import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 使用执行器（线程池）改善ChatServer一个线程对应一个连接的问题
 * 
 * @author shaoyuxia
 *
 */
class ChatServerEnhance extends ChatServer {

	private static final int corePoolSize = 128;
	private static final int maxPoolSize = 128;
	private long keepAliveTime = 60;
	private static final Log LOG = LogFactory.getLog(ChatServerEnhance.class);

	private ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
			TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

	public ChatServerEnhance(int port) {
		super(port);
	}

	public ChatServerEnhance(int port, int backlog) {
		super(port, backlog);
	}

	@Override
	protected void handleConnection(Socket socket) {
		LOG.debug("[Executor info]: ActiveCount=" + executor.getActiveCount() + ";PoolSize=" + executor.getPoolSize()
				+ ";TaskCount=" + executor.getTaskCount());
		Runnable task = () -> {
			handleSingleConnection(socket);
		};
		executor.submit(task);

	}

	@Override
	public void shutDown() {
		executor.shutdown();
	}

}
